package com.wdcloud.framework_business.base;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.wdcloud.framework_business.utils.CustomUtil;
import com.wdcloud.framework_business.wight.CustomNetErrorView;

import java.util.Timer;
import java.util.TimerTask;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Info:
 * Created by Umbrella.
 * CreateTime: 2021/3/4 16:11
 */
public abstract class BaseBusinessActivity extends AppCompatActivity {
    protected boolean isActive;
    private boolean isNetworkConnected = true;
    private View mContainer;
    private ViewGroup mRoot;
    private boolean isIgnoreNet=false;
    private Unbinder bind;
    private CustomNetErrorView customNetErrorView;
    // 两次点击按钮之间的点击间隔不能少于1000毫秒
    private static final int MIN_CLICK_DELAY_TIME = 1000;
    private static long lastClickTime;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Object layout = getLayout();
        if (layout instanceof Integer) {
            setContentView((Integer) layout);
        } else if (layout instanceof View) {
            setContentView((View) layout);
        }
        bind = ButterKnife.bind(this);
        initTitleView();
        checkNetStateInitData();
    }
    //根据界面设置title
    protected void initTitleView() {

    }
    private void checkNetStateInitData(){
        //页面让网络检查并且没有网络时候--显示无网络页面
        if (!isIgnoreCheckNet() && !CustomUtil.isNetworkConnected(this)) {
            isNetworkConnected = false;
            mContainer.setVisibility(View.GONE);
            //无网络显示内容
            if (customNetErrorView == null) {
                customNetErrorView = new CustomNetErrorView(this);
                mRoot.addView(customNetErrorView);
            }
        } else {
            mContainer.setVisibility(View.VISIBLE);
            getExtraData(getIntent());
            //从无网络状态切换到有网络状态，Resume方法中的逻辑需再次执行
            if (!isNetworkConnected) {
                isNetworkConnected = true;
                loadData();
            }
        }
    }

    /**
     * 获得bundle数据
     */
    protected void getExtraData(Intent intent) {

    }
    protected abstract Object getLayout();
    @Override
    public void setContentView(int layoutResID) {
        setContentViewWithTitle(layoutResID);
    }

    @Override
    public void setContentView(View view) {
        setContentViewWithTitle(view);
    }
    public void setContentViewWithTitle(int layoutResID)
    {
        View inflate = getLayoutInflater().inflate(layoutResID, null);
        setContentViewWithTitle(inflate);
    }
    /**
     * 设置realroot，默认是linearlayout，子类可以自定义类型
     */
    public ViewGroup genRealRootView() {
        final FrameLayout linearLayout = new FrameLayout(this);
        return linearLayout;
    }
    /**
     * 初始化数据
     */
    protected void loadData() {

    }
    public void setContentViewWithTitle(View view){
        mContainer=view;
        mRoot = genRealRootView();
        mRoot.addView(view, -1, -1);
        super.setContentView(mRoot);
    }
    /**
     * 设置rootview，默认是linearlayout，子类可以自定义类型，使titlebar可以显示不同的样式（如浮动）
     *
     * @return
     */
    public ViewGroup genRootView() {
        final LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        return linearLayout;
    }
    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isIgnoreCheckNet() && !CustomUtil.isNetworkConnected(this)) {
            return;
        }
        loadData();
        isActive = true;
    }
    /**
     * 是否忽略网络检查
     * true 直接初始化数据
     *
     * @return 默认false
     */
    protected boolean isIgnoreCheckNet() {
        return isIgnoreNet;
    }
    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }

    @Override
    protected void onDestroy() {
        isActive = false;
        super.onDestroy();
        bind.unbind();
    }

    @Override
    public void finish() {
        isActive = false;
        super.finish();
    }
    /* 按两次退出*/
    private boolean backIndex = true;
    /*物理返回按钮监听*/
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //获取的回退栈的数量,因为四个主fragment没有加入回退栈所以是0
        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
            //监听首页搜索的返回按钮
            int count = getBackStackEntryCount();
            if (count == 0 && isOneActivity()) {
                backIsTrurFalse();
            } else {
                long curClickTime = System.currentTimeMillis();
                if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
                    // 超过点击间隔后再将lastClickTime重置为当前点击时间
                    lastClickTime = curClickTime;
                    onBackPressed();
                }

            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    /**
     * 获得栈中最顶层的Activity
     *
     * @return
     */
    private boolean isOneActivity() {
        String localClassName = getLocalClassName();
        if ("MainActivity".equals(getLocalClassName())) {
            return true;
        }
        return false;
    }
    /**
     * 获取回退栈数量
     **/
    public int getBackStackEntryCount() {
        return getSupportFragmentManager().getBackStackEntryCount();
    }
    private void backIsTrurFalse() {
        if (backIndex) {
            backIndex = false;
            Toast.makeText(this, "再按一次退出！", Toast.LENGTH_SHORT).show();
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    backIndex = true;
                }
            }, 3000);
        } else {
            finish();
            super.onBackPressed();
        }
    }

}